<template>
  <div>
    <el-card style="width: 1200px; margin: 0 auto" shadow="always">
      <el-form
        :model="AddSpuListData"
        :rules="rules"
        ref="ruleForm"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item label="SPU名称" prop="spuName">
          <el-input
            size="small"
            v-model="AddSpuListData.spuName"
            placeholder="SPU名称"
          ></el-input>
        </el-form-item>
        <el-form-item label="品牌" prop="tmId">
          <el-select
            v-model="AddSpuListData.tmId"
            size="small"
            placeholder="请选择"
          >
            <el-option
              :label="Trademark.tmName"
              :value="Trademark.id"
              v-for="Trademark in TrademarkList"
              :key="Trademark.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="SPU描述" prop="description">
          <el-input
            type="textarea"
            v-model="AddSpuListData.description"
          ></el-input>
        </el-form-item>
        <el-form-item label="SPU图片" prop="spuImageList">
          <el-upload
            :action="`${BASE_API}/admin/product/upload`"
            list-type="picture-card"
            :on-success="handleAvatarSuccess"
            :on-preview="handlePictureCardPreview"
            :on-remove="handleRemove"
            :file-list="AddSpuListData.spuImageList"
          >
            <i class="el-icon-plus" />
            <template #tip>
              <div class="el-upload__tip">
                只能上传jpg/png/jpeg文件，且不超过250kb
              </div>
            </template>
          </el-upload>
          <el-dialog :visible.sync="dialogVisible">
            <img
              width="100%"
              v-if="dialogImageUrl"
              :src="dialogImageUrl"
              alt=""
            />
          </el-dialog>
        </el-form-item>
        <el-form-item label="销售属性" prop="spuSaleAttrList">
          <el-select
            v-model="baseSaleAttrStr"
            size="small"
            :placeholder="
              BaseAttrCountList.length
                ? `还剩${BaseAttrCountList.length}个属性可选`
                : '暂无数据'
            "
          >
            <el-option
              v-for="attr in BaseAttrCountList"
              :key="attr.id"
              :label="attr.name"
              :value="attr.id + ':' + attr.name"
            ></el-option>
          </el-select>
          <el-button
            class="attrbtn"
            size="small"
            type="primary"
            :disabled="baseSaleAttrStr ? false : true"
            @click="AddBaseSaleAttr"
            >添加销售属性</el-button
          >
        </el-form-item>
        <el-form-item>
          <el-table
            border
            :data="AddSpuListData.spuSaleAttrList"
            style="width: 100%"
          >
            <el-table-column type="index" label="序号" width="180" />
            <el-table-column prop="saleAttrName" label="属性名" width="180" />
            <el-table-column label="属性名名称列表">
              <template v-slot="{ row }">
                <el-tag
                  v-for="(value, index) in row.spuSaleAttrValueList"
                  :key="Math.random()"
                  closable
                  @close="closeTag(row, index)"
                  type="success"
                  v-show="row.isShowEdit"
                >
                  {{ value.saleAttrValueName }}
                </el-tag>
                <el-input
                  style="width: 100px"
                  v-show="!row.isShowEdit"
                  @change="ChangeisShowTag(row)"
                  @blur="SwitchShowTag(row)"
                  v-model="getValue"
                  ref="attrIpt"
                  size="mini"
                ></el-input>
                <el-button
                  @click="isSwitchInputorSpan(row)"
                  icon="el-icon-plus"
                ></el-button>
              </template>
            </el-table-column>
            <el-table-column label="操作">
              <template v-slot="{ row }">
                <el-button
                  @click="handleClick(row)"
                  type="danger"
                  size="mini"
                  icon="el-icon-delete"
                ></el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-form-item>
        <el-form-item>
          <el-button size="small" type="primary" @click="SaveSpuInfo"
            >保存</el-button
          >
          <el-button size="small" @click="CancelPage">取消</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import {
  getBaseSaleAttrListApi,
  getTrademarkListApi,
  SaveSpuInfoApi,
  UpdateSpuInfoApi
} from '@/api/SPUApi'
export default {
  name: 'AddSorUpdateSpu',
  data() {
    var validatePass = (rule, value, callback) => {
      // console.log(value)
      // return callback()
      if (!value.length) {
        callback(new Error('请至少添加一个销售属性'))
        return
      }
      if (!value.every((saleAttr) => saleAttr.spuSaleAttrValueList.length)) {
        callback(new Error('每个销售属性至少添加一个销售属性值'))
        return
      }
      callback()
    }
    return {
      dialogImageUrl: '',
      dialogVisible: false,
      TrademarkList: [],
      BaseSaleAttrId: '',
      BaseSaleAttrList: [],
      AddSpuListData: {
        category3Id: 0,
        spuName: '',
        description: '',
        spuImageList: [],
        spuSaleAttrList: [],
        tmId: '',
        id: 0
      },
      baseSaleAttrStr: '',
      getValue: '',
      BASE_API: process.env.VUE_APP_BASE_API,
      rules: {
        spuName: [
          { required: true, message: '请输入SPU名称', trigger: 'blur' },
          { min: 3, max: 10, message: '长度在 3 到 5 个字符', trigger: 'blur' }
        ],
        tmId: [{ required: true, message: '请选择品牌', trigger: 'change' }],
        description: [
          { required: true, message: '请输入SPU描述', trigger: 'blur' }
        ],
        spuImageList: [{ required: true, message: '请上传图片' }],
        spuSaleAttrList: [{ required: true, validator: validatePass }]
      }
    }
  },
  methods: {
    AddBaseSaleAttr() {
      const splitStr = this.baseSaleAttrStr.split(':')
      this.baseSaleAttrStr = ''

      this.AddSpuListData.spuSaleAttrList.push({
        baseSaleAttrId: +splitStr[0],
        saleAttrName: splitStr[1],
        spuSaleAttrValueList: [],
        isShowEdit: true
      })
    },
    async getTrademarkList() {
      const res = await getTrademarkListApi()
      if (res.code === 200) {
        this.TrademarkList = res.data.map((item) => {
          return {
            id: item.id,
            tmName: item.tmName
          }
        })
      }
    },
    async getBaseSaleAttr() {
      // 获取销售属性
      const res = await getBaseSaleAttrListApi()
      if (res.code === 200) {
        this.BaseSaleAttrList = res.data
      }
    },
    isSwitchInputorSpan(row) {
      row.isShowEdit = false
      row.spuSaleAttrValueList.push({
        baseSaleAttrId: +row.baseSaleAttrId
      })

      this.$nextTick(() => {
        this.$refs.attrIpt.focus()
      })
    },
    SwitchShowTag(row) {
      row.isShowEdit = true
      if (!this.getValue) {
        row.spuSaleAttrValueList.pop()
      }
      this.getValue = ''
      if (this.AddSpuListData.spuSaleAttrList.length) {
        this.$refs.ruleForm.clearValidate('spuSaleAttrList')
      }
    },
    ChangeisShowTag(row) {
      row.spuSaleAttrValueList[
        row.spuSaleAttrValueList.length - 1
      ].saleAttrValueName = this.getValue
    },
    closeTag(row, index) {
      row.spuSaleAttrValueList.splice(index)
    },
    CancelPage() {
      this.$emit('SwitchAddorUpdate', '1')
    },
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          alert('submit!')
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    resetForm(formName) {
      this.$refs[formName].resetFields()
    },
    handleRemove(file, fileList) {
      this.AddSpuListData.spuImageList =
        this.AddSpuListData.spuImageList.filter((item) => {
          if (item.id === file.id) {
            return false
          }
          return true
        })
    },
    handleAvatarSuccess(res, file) {
      this.dialogImageUrl = URL.createObjectURL(file.raw)
      this.AddSpuListData.spuImageList.push({
        imgName: file.name,
        imgUrl: file.response.data,
        status: 'success',
        uid: file.uid,
        name: file.name,
        url: file.response.data
      })
      if (this.AddSpuListData.spuImageList.length) {
        this.$refs.ruleForm.clearValidate('spuImageList')
      }
    },
    handlePictureCardPreview(file) {
      this.dialogVisible = true
    },
    handleClick(row) {
      console.log(row)
      this.AddSpuListData.spuSaleAttrList =
        this.AddSpuListData.spuSaleAttrList.filter((item) => {
          if (item.baseSaleAttrId === row.baseSaleAttrId) {
            return false
          }
          return true
        })
    },
    async SaveSpuInfo() {
      await this.$refs.ruleForm.validate()

      if (this.AddSpuListData.id) {
        const res = await UpdateSpuInfoApi({
          ...this.AddSpuListData,
          category3Id: this.$store.state.sortStore.Category3Id
        })
        if (res.code === 200) {
          this.CancelPage()
        }
      } else {
        const res = await SaveSpuInfoApi({
          ...this.AddSpuListData,
          category3Id: this.$store.state.sortStore.Category3Id
        })
        if (res.code === 200) {
          this.CancelPage()
        }
      }
    }
  },
  mounted() {
    this.getBaseSaleAttr()
    this.getTrademarkList()
    this.AddSpuListData = this.$store.state.spuStore.AddSpuListData
  },
  computed: {
    BaseAttrCountList() {
      return this.BaseSaleAttrList.filter((baseAttr) => {
        return this.AddSpuListData.spuSaleAttrList.every((spuAttr) => {
          return baseAttr.id !== spuAttr.baseSaleAttrId
        })
      })
    }
  },
  beforeDestroy() {
    this.$store.dispatch('spuStore/resetState')
  }
}
</script>

<style scoped>
.attrbtn {
  margin-left: 20px;
}
</style>
